import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/data/entities/application/major_hazard/hazard_curve_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/major_hazard/hazard_instrument_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/major_hazard/monitor/curve/curve_controller.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

const _blue = Color.fromARGB(20, 84, 120, 246);

class HazardMonitorCurvePage extends StatelessWidget {
  HazardMonitorCurvePage({super.key});

  final String equipName = Get.arguments['equipName'] as String? ?? '';
  final String equipCode = Get.arguments['equipCode'] as String? ?? '';
  final HazardInstrumentEntity? instrument = Get.arguments['data'] as HazardInstrumentEntity?;

  final controller = Get.put(HazardMonitorCurveController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: controller,
      builder: (_) {
        return Scaffold(
          body: SafeArea(
            child: RotatedBox(
              quarterTurns: 3,
              child: _buildPage(),
            ),
          ),
        );
      },
    );
  }

  Widget _buildPage() {
    return FutureBuilder(
      future: controller.getCurveData(equipCode),
      builder: (_, snapshot) {
        final data = snapshot.data;
        return Column(
          children: [
            _buildTitle(data?.isEmpty ?? true ? null : data?.last),
            _buildContent(data),
          ],
        );
      },
    );
  }

  Widget _buildTitle(HazardCurveEntity? data) {
    return Container(
      height: 40.w,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            color: AppColors.divider_color_blue,
            width: 1.w,
          ),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              IconButton(onPressed: Get.back, icon: const Icon(Icons.arrow_back)),
              AppGaps.hGap10,
              Text(
                '历史曲线图',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          Row(
            children: [
              Row(
                children: [
                  SvgPicture.asset(
                    AppImages.icon_water,
                    height: 10.w,
                    width: 10.w,
                  ),
                  AppGaps.hGap10,
                  Text('${data?.targetTypeDicName}：', style: TextStyle(fontSize: 14.sp, color: Colors.grey)),
                  Text('${data?.lastValue}${data?.unit}/${_buildDetailStatus(data?.targetStatus)}', style: TextStyle(fontSize: 14.sp, color: Colors.black)),
                ],
              ),
              AppGaps.hGap20,
              Row(
                children: [
                  SvgPicture.asset(
                    AppImages.icon_clock,
                    height: 12.w,
                    width: 12.w,
                  ),
                  AppGaps.hGap10,
                  Text(
                    data?.lastCollectTime ?? '未知',
                    style: TextStyle(color: Colors.black, fontSize: 14.w),
                  ),
                ],
              ),
              AppGaps.hGap20,
              Stack(
                alignment: Alignment.center,
                children: [
                  SvgPicture.asset(
                    AppImages.icon_red_inverted_trapezoid,
                    width: 52.w,
                    height: 24.w,
                  ),
                  Padding(
                    padding: EdgeInsets.only(right: 4.w),
                    child: Text(
                      '处置',
                      style: TextStyle(fontSize: 12.w, color: Colors.white),
                    ),
                  ),
                ],
              ),
              Stack(
                alignment: Alignment.center,
                children: [
                  SvgPicture.asset(
                    AppImages.icon_blue_trapezoid,
                    width: 52.w,
                    height: 24.w,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 4.w),
                    child: Text(
                      '消警',
                      style: TextStyle(fontSize: 12.w, color: Colors.white),
                    ),
                  ),
                ],
              ),
              AppGaps.hGap20,
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildContent(List<HazardCurveEntity>? data) {
    return Column(
      children: [
        _buildContentTitle(),
        _buildChart(data),
      ],
    );
  }

  Widget _buildContentTitle() {
    return Row(
      children: [
        Stack(
          alignment: Alignment.center,
          children: [
            SvgPicture.asset(
              AppImages.icon_red_trapezoid,
              width: 28.w,
              height: 18.w,
            ),
            Text('01', style: TextStyle(fontSize: 12.w, color: Colors.white)),
          ],
        ),
        AppGaps.hGap10,
        Text(
          equipName,
          style: const TextStyle(fontWeight: FontWeight.w500, color: Colors.black),
        ),
        AppGaps.hGap20,
        _buildSelect(HazardMonitorCurveType.liquid),
        _buildSelect(HazardMonitorCurveType.pressure),
        _buildSelect(HazardMonitorCurveType.temperature),
      ],
    );
  }

  /// Use https://pub.dev/packages/syncfusion_flutter_charts to draw chart
  Widget _buildChart(List<HazardCurveEntity>? data) {
    final list = instrument?.hazardTargetVOList;
    return data == null || data.isEmpty
        ? Padding(
            padding: EdgeInsets.symmetric(vertical: 100.w),
            child: data == null ? const CircularProgressIndicator() : const Text('无数据'),
          )
        : SizedBox(
            height: 299.w,
            child: SfCartesianChart(
              primaryXAxis: CategoryAxis(),
              legend: const Legend(isVisible: false),
              trackballBehavior: TrackballBehavior(
                enable: true,
                lineDashArray: const [10],
                lineColor: Colors.grey,
                lineWidth: 1,
                activationMode: ActivationMode.singleTap,
                shouldAlwaysShow: true,
                tooltipDisplayMode: TrackballDisplayMode.groupAllPoints,
                tooltipSettings: const InteractiveTooltip(
                  enable: true,
                  color: Colors.white,
                  borderColor: Colors.grey,
                  connectorLineColor: Colors.transparent,
                  textStyle: TextStyle(color: Colors.black)
                ),
              ),
              series: <ChartSeries>[
                SplineSeries<HazardCurveEntity, String>(
                  dataSource: data,
                  xValueMapper: (val, _) => val.lastCollectTime,
                  yValueMapper: (val, _) => val.lastValue,
                  name: controller.curveType.value.name,
                  dataLabelMapper: (datum, index) => 'DATA',
                ),
                if (list != null)
                  LineSeries<HazardCurveEntity, String>(
                    dataSource: data,
                    xValueMapper: (val, _) {
                      return val.lastCollectTime;
                    },
                    yValueMapper: (val, _) {
                      return list.first.thresholdUp;
                    },
                    name: '高报',
                    dataLabelMapper: (datum, index) => 'HIGH',
                  ),
                if (list != null)
                  LineSeries<HazardCurveEntity, String>(
                    dataSource: data,
                    xValueMapper: (val, _) {
                      return val.lastCollectTime;
                    },
                    yValueMapper: (val, _) {
                      return list.first.thresholdDown;
                    },
                    name: '低报',
                    dataLabelMapper: (datum, index) => 'LOW',
                  ),
              ],
            ));
  }

  Widget _buildSelect(HazardMonitorCurveType type) {
    return InkWell(
      onTap: () {
        controller.curveType.value = type;
        controller.update();
      },
      child: Container(
        height: 36.w,
        width: 48.w,
        decoration: BoxDecoration(
          color: controller.curveType.value == type ? _blue : null,
          // 仅底部边框
          border: Border(
            bottom: BorderSide(
              color: controller.curveType.value == type ? _blue.withAlpha(255) : Colors.white,
              width: 2.w,
            ),
          ),
        ),
        alignment: Alignment.center,
        child: Text(
          type.name,
          style: TextStyle(fontSize: 14.sp, color: _blue.withAlpha(255)),
        ),
      ),
    );
  }

  /// 高高报（hh）高报（hi）低报（lo）低低报（ll）信号量报警（si）正常（no）
  String _buildDetailStatus(String? status) {
    switch (status) {
      case 'hh':
        '高高报';
      case 'hi':
        return '高报';
      case 'lo':
        return '低报';
      case 'll':
        return '低低报';
      case 'si':
        return '信号量';
      case 'no':
        return '正常';
    }
    return '未知';
  }
}
